﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.TimeAttentsService;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.APP.Classes;
using System.Globalization;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_TimeAttMonthly : System.Web.UI.Page
    {
        private Main m = new Main();
        private SsMng ssMng = new SsMng();
        private IEmployeeTypeBLL empTypeBLL = new EmployeeTypeBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private ITimeAttMonthlyBLL TimeAttMon = new TimeAttMonthlyBLL();
        private ITimeAttendantsBLL TimeAtt = new TimeAttendantsBLL();
        private IAbsenceBLL AbsenceInfo = new AbsenceBLL();
        private IAbsenceRuleBLL AbsenceRuleInfo = new AbsenceRuleBLL();
        private IJobSiteBLL jsBLL = new JobSiteBLL();
        private TimeAttentsServiceClient taService = new TimeAttentsServiceClient();

        private const int ItemsPerRequest = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                bindEmpType();
                bindJobSite();
                bindYear();
                ddlMonth.SelectedValue = DateTime.Now.Month.ToString();
                rdoM.Checked = true;
                rdoM.Attributes.Add("onclick", "return month('" + ddlMonth.ClientID + "')");
                rdoY.Attributes.Add("onclick", "return year('" + ddlMonth.ClientID + "')");

                //PanelTitle.Visible = true;

                temp_year = string.Empty;
                temp_year_th = string.Empty;
                temp_month = string.Empty;
                temp_emp_type_seq = string.Empty;
                BindGridData();
            }
        }

        private void bindJobSite()
        {
            DataSet ds = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "", "");
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.NewRow();
            dr["job_site_seq"] = 0;
            dr["job_site_name"] = "(ทั้งหมด)";
            dt.Rows.InsertAt(dr,0 );
            cmbJobSite.DataSource = dt;
            cmbJobSite.DataBind();
            cmbJobSite.SelectedIndex = 0;
        }

        private class TimeAttendantMonthlyEnh  
        {
            public TimeAttendantMonthlyEnh(PsTimeAttendanceMonthly model, int empPosSeq, 
                string empPosRefNo, string empPosName, string empPosClass,
                int empTypeSeq, int jobSiteSeq, string empTypeName, string jobSiteName,
                string empFullName)
            {
                PsTimeAttendanceMonthly = model;
                EmpPosSeq = empPosSeq;
                EmpPosRefNo = empPosRefNo;
                EmpPosName = empPosName;
                EmpPosClass = empPosClass;
                EmpTypeSeq = empTypeSeq;
                EmpTypeName = empTypeName;
                JobSiteSeq = jobSiteSeq;
                JobSiteName = jobSiteName;
                EmpFullName = empFullName;
            }
            public PsTimeAttendanceMonthly PsTimeAttendanceMonthly { get; set; }
            public int EmpPosSeq { get; set; }
            public int EmpTypeSeq { get; set; }
            public int JobSiteSeq { get; set; }
            public string EmpTypeName { get; set; }
            public string JobSiteName { get; set; }
            public string EmpPosRefNo { get; set; }
            public string EmpPosName { get; set; }
            public string EmpPosClass { get; set; }
            public string EmpFullName { get; set; } 
        }

        private void BindGridData1()
        {
            var empDataDt = empBLL.LoadEmployees(null, Convert.ToString(Model.EmpTypeSeq), 
                (int?)null, Model.JobSiteSeq, false, "").Tables[0]; 
            empDataDt.PrimaryKey = new[]{empDataDt.Columns[0]};

            var data = new List<TimeAttendantMonthlyEnh>();
            foreach (var data2 in taService
                .ListPsTimeAttendanceMonthlies()
                .Where(o =>
                    o.WorkingYear == Model.DbYear
                    && o.WorkingMonth == Model.Month))
            {
                var emp = empDataDt.Rows.Find(data2.EmpId);
                if (emp != null)
                {
                    data.Add(new TimeAttendantMonthlyEnh(data2,
                        Convert.ToInt32(emp["POS_SEQ"]),
                        Convert.ToString(emp["POS_REF"]),
                        Convert.ToString(emp["POS_NAME"]),
                        Convert.ToString(emp["CLASS_NAME"]),
                        Convert.ToInt32(emp["EMP_TYPE_SEQ"]),
                        Convert.ToInt32(emp["Job_SITE_SEQ"]),
                        Convert.ToString(emp["EMP_TYPE_NAME"]),
                        Convert.ToString(emp["JOB_SITE_NAME"]),
                        Convert.ToString(emp["Full_Name"])));
                }
            }

            DataTable dt = new DataTable();
            dt.Columns.Add("TimeAttMonthId");
            dt.Columns.Add("EmpId");
            dt.Columns.Add("WorkingMonth");
            dt.Columns.Add("WorkingYear");
            dt.Columns.Add("PlanWorkingDayCount");

            dt.Columns.Add("ActualWorkingDayCount");
            dt.Columns.Add("LateDayCount");
            dt.Columns.Add("ValidAbsenceDayCount");
            dt.Columns.Add("InvalidAbsenceDayCount");
            dt.Columns.Add("Remarks");

            dt.Columns.Add("RecordStatus");
            dt.Columns.Add("CreatedBy");
            dt.Columns.Add("CreatedWhen");
            dt.Columns.Add("UpdatedBy");
            dt.Columns.Add("UpdatedWhen");

            dt.Columns.Add("EmpFullName");
            dt.Columns.Add("NotWorkingDayCount");
            dt.Columns.Add("EmpPosRefNo");
            dt.Columns.Add("EmpPosName");
            dt.Columns.Add("EmpClass");

            var absenceTypes = taService.SelectListAbsenceType().Where(o => o.RecordStatus != "D").ToArray();
            List<GridColumn> lgc = new List<GridColumn>();
            foreach (GridColumn c in RadGrid2.Columns)
            {
                lgc.Add(c);
            }
            lgc.Reverse();
            foreach (GridColumn c in lgc.Where(o => o.UniqueName.StartsWith("AbsenceType_")))
            {
                RadGrid2.Columns.Remove(c);
            }

            foreach (var absType in absenceTypes)
            {
                dt.Columns.Add("AbsenceType_" + absType.AbsenceTypeId);

                var newColumn = new GridBoundColumn
                {
                    DataField = "AbsenceType_" + absType.AbsenceTypeId,
                    FilterControlWidth = Unit.Percentage(100),
                    HeaderText = absType.AbsenceTypeName,
                    UniqueName = "AbsenceType_" + absType.AbsenceTypeId,
                    ShowFilterIcon = false
                };
                newColumn.HeaderStyle.ForeColor = Color.FromArgb(0, 31, 160);
                RadGrid2.Columns.Add(newColumn);
            } 
            RadGrid2.Width = Unit.Pixel(975 + (absenceTypes.Count()*100));
             

            data = data.OrderBy(o => main.ConvertDefaultInt(o.EmpPosRefNo)).ToList();

            foreach (var d in data)
            {
                DataRow dr = dt.NewRow();
                int i = 0;
                dr[i++] = d.PsTimeAttendanceMonthly.TimeAttMonthId;
                dr[i++] = d.PsTimeAttendanceMonthly.EmpId;
                dr[i++] = new DateTime(DateTime.Now.Year, d.PsTimeAttendanceMonthly.WorkingMonth.Value, 1).ToString("MMMM");
                dr[i++] = d.PsTimeAttendanceMonthly.WorkingYear + 543;
                dr[i++] = (d.PsTimeAttendanceMonthly.PlanWorkingDayCount ??0).ToString("0.# วัน");

                dr[i++] = (d.PsTimeAttendanceMonthly.ActualWorkingDayCount ?? 0).ToString("0.# วัน");
                dr[i++] = (d.PsTimeAttendanceMonthly.LateDayCount ??0).ToString("0.# วัน");
                dr[i++] = (d.PsTimeAttendanceMonthly.ValidAbsenceDayCount ??0).ToString("0.# วัน");
                dr[i++] = (d.PsTimeAttendanceMonthly.InvalidAbsenceDayCount ??0).ToString("0.# วัน");
                dr[i++] = d.PsTimeAttendanceMonthly.Remarks;

                dr[i++] = d.PsTimeAttendanceMonthly.RecordStatus;
                dr[i++] = d.PsTimeAttendanceMonthly.CreatedBy;
                dr[i++] = d.PsTimeAttendanceMonthly.CreatedWhen;
                dr[i++] = d.PsTimeAttendanceMonthly.UpdatedBy;
                dr[i++] = d.PsTimeAttendanceMonthly.UpdatedWhen;

                dr[i++] = d.EmpFullName;
                dr[i++] = (d.PsTimeAttendanceMonthly.NotWorkingDayCount ?? 0).ToString("0.# วัน");
                dr[i++] = d.EmpPosRefNo;
                dr[i++] = d.EmpPosName;
                dr[i++] = d.EmpPosClass;

                foreach (var absType in absenceTypes)
                {
                    int morningAbsence = d.PsTimeAttendanceMonthly.PsTimeAttSummaries.Count(o => o.CalAbsenceId == absType.AbsenceTypeId);
                    int afternoonAbsence = d.PsTimeAttendanceMonthly.PsTimeAttSummaries.Count(o => o.CalAbsenceAfternoonId == absType.AbsenceTypeId);
                    dr[i++] = ( (morningAbsence*0.5) + (afternoonAbsence*0.5) ).ToString("0.# วัน");
                }

                dt.Rows.Add(dr);
            }
            RadGrid2.DataSource = dt;
            RadGrid2.DataBind();
        }

        private static int working_days_count;
        private static decimal? quota_vacation;

        private void CalcSummaryWorkingStatus(string month, string year, string emp_type_seq, string job_site)
        {

            // for time culture th-TH convert to en-US 
            List<TimeAttMonthly> lmon = new List<TimeAttMonthly>();
            if (!String.IsNullOrEmpty(year))
                year = m.strYearTh2En(year);

            //get quota vacation limit   absence_type_seq = 4
            quota_vacation = 0;
            IList<rule_absence> AbsRul_lst = AbsenceRuleInfo.GetAbsenceRules(emp_type_seq, "4") ?? new List<rule_absence>();
            foreach (rule_absence ar in AbsRul_lst)
                quota_vacation = ar.day_limit == null ? 0 : ar.day_limit;

            //get emp_seq distinct from time attendant and assign value other
            IList<TimeAttendantInfo> lst = TimeAtt.GetEmpSeqDist(month, year);
            foreach (TimeAttendantInfo t in lst)
            {
                TimeAttMonthly mon = new TimeAttMonthly();
                mon.emp_seq = t.emp_seq == null ? 0 : t.emp_seq;
                mon.working_month = !String.IsNullOrEmpty(month) ? Convert.ToInt32(month) : t.working_date.Value.Month;
                mon.working_year = !String.IsNullOrEmpty(temp_year_th) ? Convert.ToInt32(temp_year_th) : DateTime.Now.AddYears(543).Year;
                mon.record_status = SystemInfo._ActiveRecordStatus;
                mon.created_by = ssMng.EmpSeqI;
                //string dtUS = DateTime.Now.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                mon.created_when = DateTime.Now; //Convert.ToDateTime(dtUS);
                mon.quota_vacation = (int) quota_vacation;
                mon.plan_working_day_count = working_days_count;
                lmon.Add(mon);
            }

            //check duplication to insert or update
            IList<hrm_ps_absence> hrm_abs_lst;
            bool chkmonlylst = false;
            foreach (TimeAttMonthly tmon in lmon)
            {
                chkmonlylst = TimeAtt.CheckDupTimeAttMonly(tmon.emp_seq.ToString(), month, year);
                hrm_abs_lst = AbsenceInfo.GetAllAbsence(temp_year_th, month, tmon.emp_seq.ToString());
                //cerate object 
                decimal? sumabsence = 0;
                int? sick_count = 0;
                decimal? sick_day_count = 0;
                decimal? private_day_count = 0;
                decimal? vacation_day_count = 0;
                decimal? delivery_day_count = 0;
                decimal? edu_day_count = 0;
                decimal? ordain_day_count = 0;
                decimal? temp_day_count = 0;
                decimal? late_day_count = 0;
                //get count each of absence types
                foreach (hrm_ps_absence i in hrm_abs_lst)
                {
                    //รวมทุกการลา  
                    sumabsence += i.day_count;
                    // 1 = ลาป่วย ,2 = ลาคลอด ,3 = ลากิจ ,4 = ลาพักผ่อน ,5 = ลาบวช ,7 = ลาศึกษา ,8 = ลาไปปฎิบัติงานนอกสถานที่ ,10 = สาย
                    switch (i.absence_type_seq)
                    {
                        case 1:
                            sick_count += 1;
                            sick_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 2:
                            delivery_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 3:
                            private_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 4:
                            vacation_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 5:
                            ordain_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 7:
                            edu_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 8:
                            temp_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        case 10:
                            late_day_count += (i.day_count != null ? i.day_count : null);
                            break;
                        default:
                            break;
                    }

                    #region [old absence count]

                    //if (i.absence_type_seq == 1)
                    //{
                    //    sick_count += 1;
                    //    sick_day_count += (i.day_count != null ? i.day_count : null);
                    //}
                    //// 2 = ลาคลอด 
                    //if (i.absence_type_seq == 2)
                    //{
                    //    delivery_day_count += 1;
                    //    delivery_day_count += (i.day_count != null ? i.day_count : null);
                    //}
                    //// 3 = ลากิจ
                    //if (i.absence_type_seq == 3)
                    //{
                    //    private_day_count += 1;
                    //    private_day_count += (i.day_count != null ? i.day_count : null);
                    //}
                    //// 4 = ลาพักผ่อน
                    //if (i.absence_type_seq == 4)
                    //{
                    //    vacation_day_count += 1;
                    //    vacation_day_count += (i.day_count != null ? i.day_count : null);
                    //}                        
                    //// 5 = ลาบวช
                    //if (i.absence_type_seq == 5)
                    //{
                    //    ordain_day_count += 1;
                    //    ordain_day_count += (i.day_count != null ? i.day_count : null);
                    //} 
                    //// 7 = ลาศึกษา อบรม
                    //if (i.absence_type_seq == 7)
                    //{
                    //    edu_day_count += 1;
                    //    edu_day_count += (i.day_count != null ? i.day_count : null);
                    //}

                    //// 8 = ลาไปปฎิบัติงานนอกสถานที่
                    //if (i.absence_type_seq == 8)
                    //{
                    //    temp_day_count += 1;
                    //    temp_day_count += (i.day_count != null ? i.day_count : null);
                    //}                    
                    //if (i.absence_type_seq == 10)
                    //{
                    //    late_day_count += 1;
                    //    late_day_count += (i.day_count != null ? i.day_count : null);
                    //}

                    #endregion [old absence count]
                }

                //get sick
                int? sick_day_count_int = m.ConvertDecimalToInt(sick_day_count);
                //get private
                int? private_day_count_int = m.ConvertDecimalToInt(private_day_count);
                //get vacation
                int? vacation_day_count_int = m.ConvertDecimalToInt(vacation_day_count);
                //get delivery
                int? delivery_day_count_int = m.ConvertDecimalToInt(delivery_day_count);
                //get education
                int? edu_day_count_int = m.ConvertDecimalToInt(edu_day_count);
                //get ordain
                int? ordain_day_count_int = m.ConvertDecimalToInt(ordain_day_count);
                //get temp
                int? temp_day_count_int = m.ConvertDecimalToInt(temp_day_count);
                //get late
                int? late_day_count_int = m.ConvertDecimalToInt(late_day_count);

                //get actual 
                int? actual_day = TimeAtt.GetActualWorkingDays(month, year, tmon.emp_seq.ToString());
                actual_day = actual_day == 0 ? null : actual_day;
                //get invalid absence 
                decimal? invalid_day = TimeAtt.GetMissWorkingDays(month, year, tmon.emp_seq.ToString());
                invalid_day = invalid_day == 0 ? null : invalid_day;

                if (!chkmonlylst)
                {
                    //Insert new record                      
                    TimeAtt.InsertTimeAttMonthly(tmon.emp_seq.ToString(), Convert.ToInt32(month)
                        , tmon.plan_working_day_count, actual_day, sumabsence, invalid_day, late_day_count_int, sick_day_count_int
                        , private_day_count_int, vacation_day_count_int, tmon.working_year, sick_count, tmon.quota_vacation
                        , delivery_day_count_int, edu_day_count_int, ordain_day_count_int, temp_day_count_int, (int) tmon.created_by
                        , tmon.created_when);
                }
                else
                {
                    //Update exist record
                    TimeAtt.UpdateTimeAttMonthly(tmon.emp_seq.ToString(), Convert.ToInt32(month)
                        , tmon.plan_working_day_count, actual_day, sumabsence, invalid_day, late_day_count_int, sick_day_count_int
                        , private_day_count_int, vacation_day_count_int, tmon.working_year, sick_count, tmon.quota_vacation
                        , delivery_day_count_int, edu_day_count_int, ordain_day_count_int, temp_day_count_int, ssMng.EmpSeqI
                        , DateTime.Now);
                }
            }


        }

        private void CalcWorkingStatus(string month, string year)
        {
            if (String.IsNullOrEmpty(month)) return;

            year = m.strYearTh2En(year);
            DataSet ds;

            IList<TimeAttendantInfo> lstTimeAtt = TimeAtt.GetTimeAtt_NonStatus(month, year);
            foreach (TimeAttendantInfo item in lstTimeAtt)
            {
                int working_seq = item.working_seq;
                string working_date = item.working_date == null ? "" : item.working_date.ToString();
                string emp_seq = item.emp_seq == null ? "" : item.emp_seq.ToString();
                int working_start = m.ConvertTimeToInt(item.working_start);
                int working_end = m.ConvertTimeToInt(item.working_end);

                string[] arr = working_date.Split(' ');
                string temp_working_date = arr[0] != null ? arr[0].ToString() : working_date;
                arr = temp_working_date.Split('/');
                int n = Convert.ToInt32(arr[2].ToString());
                if (n > 2550) n -= 543;
                temp_working_date = n + "-" + arr[1] + "-" + arr[0];

                int iFlag = 0;
                DateTime? iStart_Date = new DateTime();
                DateTime? iEnd_Date = new DateTime();
                string iStart_Time = string.Empty;
                string iEnd_Time = string.Empty;

                DateTime d = Convert.ToDateTime(working_date);
                temp_working_date = d.Date.ToString("yyyy-MM-dd", new CultureInfo("en-US"));
                IList<hrm_ps_absence> lstAbsenceInfo = AbsenceInfo.GetAbsence(temp_working_date, emp_seq);
                if (lstAbsenceInfo.Count > 0)
                {
                    //พบการลา  ลา A | มาสาย L                   
                    //iFlag 1=ลาเช้า, 2=ลาบ่าย, 3=ลาทั้งวัน, 0=ไม่สามารถระบุได้
                    foreach (hrm_ps_absence i in lstAbsenceInfo)
                    {
                        iStart_Date = i.start_date;
                        iEnd_Date = i.end_date;
                        iStart_Time = i.start_time;
                        iEnd_Time = i.end_time;
                    }

                    iFlag = CalcAbsenceDay(item.working_date, iStart_Date, iEnd_Date, iStart_Time, iEnd_Time);

                    if (iFlag == 1)
                    {
                        if (working_end >= 1630)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาเช้า";
                        }
                        else if (working_end == 0)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาเช้า ขาดบ่าย";
                        }
                        else if (working_end < 1630)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาเช้า ออกก่อน";
                        }
                    }
                    else if (iFlag == 2)
                    {
                        if (working_start <= 830)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาบ่าย";
                        }
                        else if (working_start == 0)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาบ่าย ขาดเช้า";
                        }
                        else if (working_start > 830)
                        {
                            item.working_status = "A";
                            item.remarks = "ลาบ่าย สายเช้า";
                        }
                    }
                    else if (iFlag == 3)
                    {
                        item.working_status = "A";
                        item.remarks = "ลาทั้งวัน";
                    }
                    else
                    {
                        continue;
                    }

                    #region[old absence]

                    //if (iFlag == 1) { 
                    //    if((working_start <= 1300)&&(working_end >= 1630)){
                    //        item.working_status = "A";
                    //        item.remarks = "ลาเช้า";
                    //    }
                    //    else if ((working_start > 1300) || (working_end < 1631))
                    //    {
                    //        item.working_status = "A";
                    //        item.remarks = "ลาเช้า สายบ่ายหรือออกก่อนเวลา";
                    //    }
                    //    else {
                    //        item.working_status = "A";
                    //        item.remarks = "ลาเช้า ขาดบ่าย";
                    //    }
                    //}
                    //else if (iFlag == 2) {
                    //    if ((working_start <= 830) && (working_end >= 1200))
                    //    {
                    //        item.working_status = "A";
                    //        item.remarks = "ลาบ่าย";
                    //    }
                    //    else if ((working_start > 831) || (working_end < 1200))
                    //    {
                    //        item.working_status = "A";
                    //        item.remarks = "ลาบ่าย สายเช้าหรือออกก่อนเวลา";
                    //    }
                    //    else
                    //    {
                    //        item.working_status = "A";
                    //        item.remarks = "ลาบ่าย ขาดเช้า";
                    //    }
                    //}
                    //else if (iFlag == 3){
                    //    item.working_status = "A";
                    //    item.remarks = "ลาทั้งวัน";
                    //}
                    //else{
                    //    return;
                    //}

                    #endregion[old absence]

                }
                else
                {
                    // ขาดเช้า = 1 | ขาดบ่าย = 2 | ขาด = 3 | สาย = 4 | ออกก่อน = 5 | ปกติ = 6
                    iFlag = CalcMissingDay(working_start, working_end);

                    if (iFlag == 1)
                    {
                        item.working_status = "N";
                        item.remarks = "ขาดเช้า";
                    }
                    else if (iFlag == 2)
                    {
                        item.working_status = "N";
                        item.remarks = "ขาดบ่าย";
                    }
                    else if (iFlag == 3)
                    {
                        item.working_status = "N";
                        item.remarks = "ขาดทั้งวัน";
                    }
                    else if (iFlag == 4)
                    {
                        item.working_status = "L";
                        item.remarks = "สาย";
                    }
                    else if (iFlag == 5)
                    {
                        item.working_status = "L";
                        item.remarks = "ออกก่อน";
                    }
                    else if (iFlag == 6)
                    {
                        item.working_status = "W";
                        item.remarks = "ปกติ";
                    }
                    else
                    {
                        continue;
                    }

                    #region[old missing]

                    //เข้าปกติ เข้า 810  ออก 1640
                    //if ((working_start <= 830) && (working_end >= 1630))
                    //{
                    //    item.working_status = "W";
                    //}
                    ////เข้า 810  ออก 1200
                    //else if ((working_start <= 830) && (working_end < 1300)) {
                    //    item.working_status = "N";
                    //    item.remarks = "ขาดบ่าย";
                    //}
                    ////เข้า 810  ออก 1600
                    //else if ((working_start <= 830) && (working_end > 1300) && (working_end < 1630))
                    //{
                    //    item.working_status = "W";
                    //    item.remarks = "ออกก่อน";
                    //}
                    ////เข้า 840  ออก 1640
                    //else if ((working_start > 830) && (working_start < 901) && (working_end >= 1630))
                    //{
                    //    item.working_status = "L";
                    //    item.remarks = "สายเช้า";
                    //}
                    ////เข้า 840  ออก 1600
                    //else if ((working_start > 830) && (working_start < 901) && (working_end < 1630))
                    //{
                    //    item.working_status = "L";
                    //    item.remarks = "สายเช้า ออกก่อนเวลา";
                    //}
                    ////เข้า 840  ออก 1200
                    //else if ((working_start > 830) && (working_start < 901) && (working_end < 1300))
                    //{
                    //    item.working_status = "N";
                    //    item.remarks = "สายเช้า ขาดบ่าย";
                    //}
                    //else if ((working_start > 900) && (working_end < 1301))
                    //{
                    //    item.working_status = "N";
                    //    item.remarks = "ขาด";
                    //}
                    ////เข้า 1210  ออก 1640
                    //else if ((working_start <= 1300) && (working_end >= 1630))
                    //{
                    //    item.working_status = "N";
                    //    item.remarks = "ขาดเช้า";
                    //} 
                    ////เข้า 1300  ออก 1610
                    //else if ((working_start <= 1300) && (working_end < 1630))
                    //{
                    //    item.working_status = "N";
                    //    item.remarks = "ขาดเช้า ออกก่อน";
                    //}
                    ////เข้า 0  ออก 0
                    //else if ((working_start == 0) && (working_end == 0))
                    //{
                    //    item.working_status = "N";
                    //    item.remarks = "ขาด";
                    //}
                    //else
                    //{
                    //    return;
                    //}

                    #endregion[old missing]
                }

                //update ข้อมูลการทำงาน
                ds = new DataSet();
                DataRowCollection drc;
                ds = TimeAtt.LoadTimeAttendants("", working_date, "", emp_seq);
                if (ds.Tables.Count > 0)
                {
                    drc = ds.Tables[0].Rows;
                    TimeAtt.UpdateStatus(Int32.Parse(drc[0]["WORKING_SEQ"].ToString())
                        , item.working_status
                        , item.remarks
                        , ssMng.EmpSeqI);
                    drc.Clear();
                }
                //IList<TimeAttendantInfo> tlst = TimeAtt.LoadTimeAttendants_NewMod(working_date, emp_seq);
                //if (tlst.Count > 0)
                //{
                //    foreach (TimeAttendantInfo sitem in tlst) {
                //        TimeAtt.UpdateStatus(sitem.emp_seq != null ? (int)sitem.emp_seq:0
                //        , item.working_status
                //        , item.remarks
                //        , ssMng.EmpSeqI);
                //    }                       
                //}


            }

        }

        private int CalcMissingDay(int iWorking_Start, int iWorking_End)
        {
            int iFlag = 0;
            //Normal  830-1630
            if ((iWorking_Start <= 830) && (iWorking_End >= 1630))
            {
                iFlag = 6;
            }
            else if ((iWorking_Start == 0) && (iWorking_End == 0))
            {
                iFlag = 3;
            }
            else if ((iWorking_Start <= 830) && (iWorking_End < 1630))
            {
                if (iWorking_End <= 1300)
                    iFlag = 2;
                else
                    iFlag = 5;
            }
            else if ((iWorking_Start > 830) && (iWorking_End >= 1630))
            {
                if (iWorking_Start < 901)
                    iFlag = 4;
                else
                    iFlag = 1;
            }

            return iFlag;
        }

        private int CalcAbsenceDay(DateTime? working_date, DateTime? iAbsStart_Date
            , DateTime? iAbsEnd_Date, string iAbsStart_Time, string iAbsEnd_Time)
        {
            int iFlag = 0;

            if ((working_date > iAbsStart_Date) && (working_date < iAbsEnd_Date))
            {
                iFlag = 3;
            }
            else if ((working_date == iAbsStart_Date) && (iAbsStart_Date == iAbsEnd_Date))
            {
                if (iAbsStart_Time.Equals("M") && iAbsEnd_Time.Equals("M"))
                    iFlag = 1;
                else if (iAbsStart_Time.Equals("A") && iAbsEnd_Time.Equals("A"))
                    iFlag = 2;
                else if (iAbsStart_Time.Equals("M") && iAbsEnd_Time.Equals("A"))
                    iFlag = 3;
            }
            else if ((working_date == iAbsStart_Date) && (iAbsStart_Date < iAbsEnd_Date))
            {
                if (iAbsStart_Time.Equals("M"))
                    iFlag = 3;
                else if (iAbsStart_Time.Equals("A"))
                    iFlag = 2;
            }
            else if ((working_date == iAbsEnd_Date) && (iAbsStart_Date < iAbsEnd_Date))
            {
                if (iAbsEnd_Time.Equals("M"))
                    iFlag = 1;
                else if (iAbsEnd_Time.Equals("A"))
                    iFlag = 3;
            }


            return iFlag;
        }

        private static string temp_year;
        private static string temp_year_th;
        private static string temp_month;
        private static string temp_emp_type_seq;
        private Main main = new Main();
         
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        private void bindEmpType()
        {
            IList<EmployeeTypeInfo> infoList = empTypeBLL.ListEmployeeTypes();
            infoList.Insert(0, new EmployeeTypeInfo(0, "(ทั้งหมด)", "", null,null));
            ddlEmployeeType.DataSource = infoList;
            ddlEmployeeType.DataBind();
            ddlEmployeeType.SelectedIndex = 0;
        }

        private void bindYear()
        {
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("Name");
            for (int i = 2500; i <= 2600; i++)
            {
                dt.Rows.Add(Convert.ToString(i));
            }
            cmbFilterYear.DataSource = dt;
            cmbFilterYear.DataBind();
            cmbFilterYear.SelectedValue = Convert.ToString(Int32.Parse(DateTime.Today.Year.ToString()) + 543);
        }

        private void BindGridData()
        {
            DataTable dt;
            string empTyp = ddlEmployeeType.SelectedValue.Length > 0 ? ddlEmployeeType.SelectedValue : null;
            string jobSite = cmbJobSite.SelectedValue.Length > 0 ? cmbJobSite.SelectedValue : null;
            string year = cmbFilterYear.SelectedValue;
            string month = rdoM.Checked == true ? ddlMonth.SelectedValue : null;
            var ds = TimeAtt.LoadTimeAttMonthly(empTyp, jobSite, year, month);
            dt = ds != null ? ds.Tables[0] : new DataTable();

            // Old
            RadGrid1.DataSource = dt;
            if (dt.Rows.Count >= 0)
            {
                RadGrid1.MasterTableView.GroupByExpressions.Clear();

                if (rdoY.Checked)
                {
                    GridGroupByExpression g = new GridGroupByExpression(RadGrid1.Columns[2]);
                    RadGrid1.MasterTableView.GroupByExpressions.Add(g);

                    GridGroupByExpression g2 = new GridGroupByExpression(RadGrid1.Columns[3]);
                    RadGrid1.MasterTableView.GroupByExpressions.Add(g2);
                }
                else
                {
                    GridGroupByExpression g = new GridGroupByExpression(RadGrid1.Columns[3]);
                    RadGrid1.MasterTableView.GroupByExpressions.Add(g);
                }

                RadGrid1.DataBind();
            }
            BindGridData1();
        }

        //protected void cmbJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        //{
        //    DataSet ds = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "", e.Text);
        //    DataTable dt = ds.Tables[0];

        //    int itemOffset = e.NumberOfItems;
        //    int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
        //    e.EndOfItems = (endOffset == dt.Rows.Count);
        //    int j = 0;
        //    for (int i = itemOffset; i < endOffset; i++)
        //    {
        //        cmbJobSite.Items.Add(new RadComboBoxItem(dt.Rows[i]["JOB_SITE_NAME"].ToString(), dt.Rows[i]["JOB_SITE_SEQ"].ToString()));

        //        TableRow tr = new TableRow();
        //        TableCell tdFieldName = new TableCell();
        //        Label lblFieldName = new Label();
        //        lblFieldName.Text = dt.Rows[i]["JOB_SITE_NAME"].ToString();
        //        tdFieldName.Width = Unit.Pixel(150);
        //        tdFieldName.Controls.Add(lblFieldName);
        //        tr.Cells.Add(tdFieldName);

        //        ((Table) cmbJobSite.Items[j].FindControl("tableJobSite")).Controls.Add(tr);
        //        j++;
        //    }
        //    e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        //}

        protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["time_att_month_seq"]);
                TimeAtt.DeleteTimeAttMonthly(seq, ssMng.EmpSeqI);
            }
            if (e.CommandName == "ExpandCollapse")
                return;

            BindGridData();
        }
        protected void RadGrid2_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["TimeAttMonthId"]);
                TimeAtt.DeleteTimeAttMonthly(seq, ssMng.EmpSeqI);
            }
            if (e.CommandName == "ExpandCollapse")
                return;

            BindGridData();
        }
        
        protected void btnShow_Click(object sender, EventArgs e)
        {
            BindGridData();
        }
        public FilterModel Model
        {
            get
            {
                var model = new FilterModel
                {
                    EmpTypeSeq = main.ConvertNullIntMakeZeroAsNull(ddlEmployeeType.SelectedValue),
                    JobSiteSeq = main.ConvertNullIntMakeZeroAsNull(main.ConvertNullIntMakeZeroAsNull(cmbJobSite.SelectedValue) == null ? SystemInfo._JobsiteInternal : cmbJobSite.SelectedValue),
                    DbYear = main.ConvertDefaultInt(cmbFilterYear.SelectedValue) - 543
                };
                if (model.EmpTypeSeq == 0)
                {
                    model.EmpTypeSeq = null;
                }
                if (model.JobSiteSeq == 0)
                {
                    model.JobSiteSeq = null;
                }
                int month = main.ConvertDefaultInt(ddlMonth.SelectedValue);
                if (month == 0) throw new Exception("ต้องเลือกเดือน");

                model.Month = month;
                return model;
            }
        }
        public class FilterModel
        {
            public int? EmpTypeSeq { get; set; }
            public int? JobSiteSeq { get; set; }
            public int DbYear { get; set; }
            public int Month { get; set; }
        }
    }
}